package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.domain.StrategyComment;
import cn.wolfcode.luowowo.query.StrategyQuery;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.service.*;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.DbCallback;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyRepository strategyRepository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public Strategy get(String id) {
        return strategyRepository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> list() {
        return strategyRepository.findAll();
    }


    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        // 查询条件
        Query query = new Query();

        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        if (StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }

        // 拼接高级查询条件
        if (StringUtils.hasLength(qo.getKeyword())) {
            query.addCriteria(Criteria.where("name").regex(".*"+qo.getKeyword()+".*"));
        }

        // 列表数据
        PageRequest request = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");

        return DBHelper.query(template,Strategy.class,query,request);
    }

    @Override
    public void changeStateValue(String id, int state) {

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("state",state);
        template.updateMulti(query,update,Strategy.class);

    }

    @Override
    public void saveOrUpdate(Strategy strategy) {

        // 1. 根据选择的 catalogId 获取( destId 和 destName ) 以及 catalogName
        StrategyCatalog strategyCatalog = strategyCatalogService.get(strategy.getCatalogId());
        strategy.setDestId(strategyCatalog.getDestId());        // destId
        strategy.setDestName(strategyCatalog.getDestName());    // destName
        strategy.setCatalogName(strategyCatalog.getName());     // catalogName

        // 2. 通过主题 id 获取主题 name ( themeName )
        strategy.setThemeName(strategyThemeService.get(strategy.getThemeId()).getName());

        // 3. 先通过调用吐司方法,找到选择的分类是否是中国
        ArrayList<Destination> list = new ArrayList<>();
        List<Destination> toastsInfo = destinationService.getToastsInfo(list, strategy.getDestId());
        if(toastsInfo != null || toastsInfo.size() > 0){
            if ("中国".equals(toastsInfo.get(0).getName())) {
                // 国内
                strategy.setIsabroad(strategy.ABROAD_NO);
            }else{
                // 国外
                strategy.setIsabroad(strategy.ABROAD_YES);
            }
        }

        // 先判断是更新还是添加
        if (StringUtils.hasLength(strategy.getId())) {

            // 创建更新条件对象
            Query query = new Query();
//            Criteria criteria = new Criteria();
//            criteria.where("_id").is(strategy.getId());
            query.addCriteria(Criteria.where("_id").is(strategy.getId()));
            // 更新操作
            DBHelper.update(template,query,strategy,"destId","destName","themeId","themeName","catalogId"
                    ,"catalogName","title","subTitle","summary","coverUrl","isabroad","state","content");

        }else{
            // 如果是添加操作,也需要处理一些表单没有提交的数据,防止置空
            strategy.setId(null);
            // 添加时间
            strategy.setCreateTime(new Date());
            strategyRepository.save(strategy);
        }
    }

    @Override
    public List<Strategy> findByCatalogId(String id) {

        List<Strategy> strategies = strategyRepository.findByCatalogId(id);
        return strategies;
    }

    @Override
    public List<Strategy> findByDestIdOrderByDesc(String destId) {

        PageRequest viewnum = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Strategy> strategies = strategyRepository.findByDestId(destId,viewnum);

        return strategies;
    }

    @Override
    public void updateStatisVo(StrategyStatisVO vo) {
        // 创建更新条件对象
        Query query = new Query();

        // 将 vo 对象中的 strategyId 攻略 id 作为查询条件,查询出 Strategy 对象信息
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));

        // 创建 Strategy 对象,将vo对象中对应的属性值,拷贝到 strategy 对象中,准备做数据更新
        Strategy strategy = new Strategy();
        BeanUtils.copyProperties(vo,strategy);

        // 进行数据更新
        DBHelper.update(template,query,strategy,"viewnum","replynum","favornum","thumbsupnum");

    }

    @Override
    public List<Strategy> getByDestName(String keyword) {

        return strategyRepository.findByDestName(keyword);
    }


}
